package zisu.rabbit.rabbitmqspring.producer;

import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;
import sun.net.www.MessageHeader;

import java.util.Map;

/**
 * @Author: 蔡翔
 * @Date: 2019/8/16 10:33
 * @Version 1.0
 */
@Component
public class RabbitSender {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    // ConfirmCallback用于监听 Broker端给我们返回的确认请求
    final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
        @Override
        public void confirm(CorrelationData correlationData, boolean ack, String cause) {
            System.err.println("correlationData:"+correlationData);
            System.err.println("ack:"+ack);
            if(!ack){
                System.err.println("异常处理。。。");
            }
        }
    };

    //做消息 不可达，做二次处理，如补偿处理
    final RabbitTemplate.ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {
        @Override
        public void returnedMessage(org.springframework.amqp.core.Message message, int replyCode, String replyText, String exchange, String routingKey) {
            System.err.println("return exchange:"+exchange+",routingKey:"+routingKey+",replyCode"+replyCode+",replyText："+replyText);
        }
    };


    public void send(Object message, Map<String,Object> properties) throws Exception{
        MessageHeaders mhs = new MessageHeaders(properties);
        Message message1 = MessageBuilder.createMessage(message,mhs);

        rabbitTemplate.setConfirmCallback(confirmCallback);  //设置消息的监听请求 回送
        rabbitTemplate.setReturnCallback(returnCallback);
        rabbitTemplate.convertAndSend("exchange-1","springboot.hello",message1);
    }
}
